package com.young.common.client.ums;

import com.young.common.util.CookieUtil;
import com.young.common.util.StringUtils;
import com.young.interfaces.ums.model.SsoVerifyDTO;
import com.young.interfaces.ums.model.User;
import com.young.interfaces.ums.service.IUmsOutService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 本地环境下的登录用户服务
 * @author imrookie
 * @date 2018/9/30
 */
@Service("localLoginUser")
@ConditionalOnProperty(
        name = "young.interceptor.ums-client-interceptor.loginUserService",
        havingValue = "localLoginUser",
        matchIfMissing = false
)
public class LocalLoginUser implements ILoginUser {

    private static final Logger logger = LoggerFactory.getLogger(LocalLoginUser.class);

    @Resource
    IUmsOutService umsOutService;

    /**
     * 获取当前登录用户信息
     * 1.从请求体和cookie还有header中获取令牌
     * 2.调用服务验证token
     *
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        String token = request.getParameter("_token");
        Cookie cookie = CookieUtil.getCookie(request, "_token");//从cookie中取令牌
        if (cookie != null && StringUtils.isNotBlank(cookie.getValue())){//cookie存在令牌
            if (StringUtils.isNotBlank(token)){//存在入参token
                if (!token.equals(cookie.getValue())){//cookie和传入的不一致,报错
                    logger.warn("[本地登录用户服务] cookie与请求体不一致,cookie={},请求体={}", cookie.getValue(), token);
                    return null;
                }
            }
            token = cookie.getValue();
        }
        //从header中取
        if (StringUtils.isBlank(token)) {
            token = request.getHeader("_token");
        }
        if (StringUtils.isBlank(token)){//cookie/入参/header都为空
            logger.debug("[本地登录用户服务] token令牌为空:cookie/请求体/header都没有token信息,URL={}", request.getRequestURL());
            return null;
        }

        try {
            //验证token有效性并返回用户信息(若有效的话)
            SsoVerifyDTO ssoVerifyDTO = umsOutService.verifySSO(token);
            if (ssoVerifyDTO != null && ssoVerifyDTO.isSuccess()){
                logger.debug("[本地登录用户服务] 当前登录用户信息打印:{}", ssoVerifyDTO.getUser());
                return ssoVerifyDTO.getUser();
            }

        } catch (Exception e) {
            logger.error("[本地登录用户服务] token验证发生异常,token={}", token, e);
        }
        return null;
    }

    /**
     * 校验用户是否有权限访问
     *
     * @param user 用户
     * @param uri  uri
     * @return
     */
    @Override
    public boolean canAccessUri(User user, String uri) {
        return umsOutService.canAccessUri(user.getId(), uri);
    }
}
